package com.sun.communit;

/**
 * 两个线程对资源类进行操作
 * 一个线程+1，一个线程减1
 */
public class ThreadComminute {
    public static void main(String[] args) {
        OperateNum operateNum = new OperateNum();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    operateNum.add();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"AA").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    operateNum.desc();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"BB").start();
    }
}


class OperateNum{
    int initNum = 0;

    //加数
    public synchronized void add() throws InterruptedException {
        while (initNum != 0 ){
          this.wait();
        }
        initNum++;
        System.out.println(Thread.currentThread().getName() + ":" + initNum);
        this.notifyAll();
    }

    public synchronized void desc() throws InterruptedException {
        while(initNum !=1){
            this.wait();
        }
        initNum--;
        System.out.println(Thread.currentThread().getName() + ":" + initNum);
        this.notifyAll();
    }
}
